package com.cerosoft.google.api;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.net.Uri;
import android.util.Log;

public class GoogleContacts {
	private GoogleAccount account;
	
	public GoogleContacts(GoogleAccount account) {
		this.account = account;
	}
	
    private String parseXML(InputStream is) throws GoogleServiceException {
    	DocumentBuilder builder;
		try {
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builder.parse(is);
			NodeList entryList = doc.getElementsByTagName("entry");
			if (entryList.getLength() > 0) {
				Element entry = (Element)entryList.item(0);
				NodeList emailList = entry.getElementsByTagName("gd:email");
				if (emailList.getLength() > 0) {
					Element emailItem = (Element)emailList.item(0);
					String ip = emailItem.getAttribute("address");
					Log.i("paser", "ip = " + ip);
					return ip;
				}
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new GoogleServiceException("Can not parse the server data");
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new GoogleServiceException("Can not parse the server data");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new GoogleServiceException("Can not parse the server data");
		}   	
		return null;
    }
    
    /**
     * Search the contact and return the address field value.
     * @param searchKey
     * @return The address field value
     */
    public String getContact(String searchKey) throws GoogleServiceException {
    	String ip = null;
     	HttpClient client = new DefaultHttpClient();
     	String queryString = String.format("https://www.google.com/m8/feeds/contacts/%s/full?q=%s",
     			Uri.encode(account.getUsername()), Uri.encode(searchKey));
     	HttpGet get = new HttpGet(queryString);
     	get.addHeader("GData-Version", "3.0");
     	get.addHeader("Authorization", "GoogleLogin auth=" + account.getAuth());
     	
     	try {
     		HttpResponse response = client.execute(get);
     		HttpEntity respData = response.getEntity();
			InputStream is = respData.getContent();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			int read = 0;
			byte[] data = new byte[2048];
			while ((read = is.read(data)) != -1) {
				bos.write(data, 0, read);
			}	
			
			if (response.getStatusLine().getStatusCode() == 200) {
				ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
				ip = parseXML(bis);
			}
			else {
				String code = String.format("resposne codes = %d", response.getStatusLine().getStatusCode());
				String content = bos.toString("UTF-8");
				Log.e("response", code + ":" + content);
				throw new GoogleServiceException(code + " : " + content);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new GoogleServiceException(e.toString());
		}
    	return ip;
    }
}
